<?php
namespace app\api\controller;

use app\common\controller\BaseController;
use app\common\library\Oss as OssClient;
use app\common\service\TokenService;
use app\common\service\TencentService;
use app\common\library\Oss;
use think\facade\Request;
use app\common\utils\Http;
use think\facade\Log;
use app\common\utils\JsonResponse;
use think\facade\Db;
use think\facade\Validate;
use think\facade\Filesystem;

class Index extends BaseController
{
    public function index()
    {
        $result = ['name' => 'api'];

        return $this->success($result, 'api success');
    }

    /**
     * 以图搜索产品ID
     */
    public function searchProductByImage()
    {
        try {
            
            $params = Request::only(['file_id']);
            // 获取文件信息
            $fileInfo = Db::name('oss_file')->field('id,file_name,file_path,file_url')->where('id', $params['file_id'])->find();
           
            if (empty($fileInfo)) {
                return JsonResponse::error('文件不存在');
            }
            //通过id获取图片信息
            // 获取token
            $token = TokenService::getInstance()->getToken();
            if (empty($token)) {
                return JsonResponse::error('获取授权失败！');
            }
            
            // 准备请求参数
            $requestData = [
                'table_name' => 't_product_group',
                'url' => $fileInfo['file_url']
            ];
            $headers = ['Authorization:Bearer '.$token,'Content-Type: multipart/form-data'];
            // 调用第三方接口
            $response = Http::CURL('http://ai.zhuanfa.jijianjide.com:8800/api/furniture/identify/search', $requestData,'POST',$headers);

            // print_r($response);die;
            // 解析响应
            $result = json_decode($response, true);
            if (!$result || !isset($result['code'])) {
                return JsonResponse::error('接口调用失败');
            }

            // 处理响应结果
            if ($result['code'] !== 200) {
                return JsonResponse::error($result['msg'] ?? '搜索失败');
            }
            
            $data = [];
            $res = [];
            $product_group = [];
            if(isset($result['data']['list'])){
                foreach($result['data']['list'] as $key => $item){     
                    $file = $this->uploadBase64Image($item['img_base64']);
                    if($file['code'] == 200){
                        if($file['data']['id']){
                            if(!isset($data['file_id'])){
                                $data['file_id'] = $file['data']['id'];
                            }else{
                                $data['file_id'] .= ','.$file['data']['id'];
                            }
                            $res[$key]['data'] = $file['data'];
                        }else{
                            return JsonResponse::error('上传图片失败');
                        }
                    }else{
                        return JsonResponse::error($file['msg'] ?? '上传图片失败');
                    }
                    //获取产品组数据

                    unset($item['img_base64']);
                    // 提取所有产品ID
                    $product_ids = array_column($item['product_ids'], 'product_id');
                    // 创建distance映射关系
                    $distanceMap = array_column($item['product_ids'], 'distance', 'product_id');
                    $products = Db::name('t_product_group')->alias('a')
                        ->leftJoin('sys_file b','a.main_img = b.id')
                        ->field('a.id,a.name,a.main_img,b.file_name,b.width,b.height')
                        ->where('a.id', 'in', $product_ids)->select()->each(function($product) {
                            if ($product['file_name'] && strpos($product['file_name'], 'http') === false) {
                                $product['file_name'] = 'https://sanyanhu.oss-cn-shenzhen.aliyuncs.com/' . $product['file_name'];
                            }
                            $product['id'] =strval($product['id']);
                            return $product;
                        })
                        ->toArray();

                    if($products){
                        // 添加distance字段并排序
                        foreach ($products as &$product) {
                            $product['distance'] = $distanceMap[$product['id']];
                        }
                        // 按distance从小到大排序
                        usort($products, function($a, $b) {
                            return $a['distance'] <=> $b['distance'];
                        });

                    }
                    $res[$key]['product_group'] = $products;                                   
                    $product_group[] = $item;
                    
                }
            }
            $data['user_id'] = request()->userId;
            $data['search_file_id']=$params['file_id'];
            $data['product_group'] = json_encode($product_group);
            $data['create_time'] = time();
            $data['update_time'] = time();
            if(count($data) > 0){
                if(Db::name('search_product')->insert($data) === false){
                    return JsonResponse::error('保存失败');
                }
            }

            return JsonResponse::success($res ?? [], '搜索成功');

        } catch (\Exception $e) {
            \think\facade\Log::error('以图搜索产品ID失败: ' . $e->getMessage());
            return JsonResponse::error('系统错误');
        }
    }

    // 查询产品组数据
    public function Productgroup(){
        $group = Request::param('group');
        $product = Db::name('t_product_group')->alias('a')->leftJoin('sys_file b','a.main_img = b.id')
            ->field('a.id,a.name,a.main_img,b.file_name,b.width,b.height')->where('a.id', 'in',$group)->select()->toArray();
        foreach($product as &$item){
            if($item['file_name'] && strpos($item['file_name'], 'http') === false){
                $item['file_name'] = 'https://sanyanhu.oss-cn-shenzhen.aliyuncs.com/'. $item['file_name'];
            }
        }
        return JsonResponse::success($product);
    }

    // 查询产品具体数据
    public function ProductDetails(){

        $group_id = Request::param('group_id');
        //获取产品组具体数据
        //需要名称，图片，id，工厂名字，来源，发货地址 ->leftJoin('t_store_delivery_addr b','a.delivery_addr_id = b.id')
        $product = Db::name('t_product')->alias('a')->leftJoin('t_product_group_relation b','a.id = b.product_id')
        ->leftJoin('t_store c','a.store_id = c.pk_store_id')->field('a.id,b.group_id,a.store_id,a.store_name,c.store_pic,a.product_name,
        a.price,a.min_price,a.max_price,a.pic,a.delivery_addr_id,a.city_code,a.city,(a.sale+a.fictitious_sale) as sale,b.type')
        ->where('b.group_id', $group_id)->order('a.price asc,a.min_price asc,a.max_price asc')->select()->toArray();
        if(!$product){
            return JsonResponse::error('检测不到产品组数据！');
        }
        $city_code = [];
        $factory_count = [];
        $price_ranges_val = [];
        $need_price_ranges = [];        

        // 获取所有产品的SKU数据
        $all_skus = [];
        foreach ($product as &$item) {
            $item['group_id'] = strval($item['group_id']);
            $price_ranges_val[] = intval($item['min_price']);
            $price_ranges_val[] = intval($item['max_price']);
            // 处理图片URL
            if($item['pic'] && strpos($item['pic'], 'http') === false){
                $item['pic'] = 'https://sanyanhu.oss-cn-shenzhen.aliyuncs.com/' . $item['pic'];
            }
            if($item['store_pic'] && strpos($item['store_pic'], 'http') === false){
                $item['store_pic'] = 'https://sanyanhu.oss-cn-shenzhen.aliyuncs.com/' . $item['store_pic'];
            }
            // 获取产品的SKU数据
            $skus = Db::name('t_sku')
                ->where('product_id', $item['id'])
                ->field('id,price,sale')->order('price asc')->select()->toArray();
                
            $item['skus'] = $skus;
            $all_skus = array_merge($all_skus, $skus);

            // 统计城市数量
            if(!isset($city_code[$item['city_code']])){
                $city_code[$item['city_code']] = [
                    'count' => 1,
                    'city' => $item['city'],
                    'store_id' => $item['store_id'],
                    'city_code' => $item['city_code']
                ];
            } else if($city_code[$item['city_code']]['store_id'] != $item['store_id']){
                $city_code[$item['city_code']]['count'] += 1;
            }

            // 统计工厂数量
            if(!isset($factory_count[$item['store_id']])){
                $factory_count[$item['store_id']] = 1;
            } else {
                $factory_count[$item['store_id']] += 1;
            }
        }
        //$price_ranges_val = [160, 70, 150, 1100, 588, 999, 1600, 3000];
        // 计算最大和最小价格
        $max_price = max($price_ranges_val);
        $min_price = min($price_ranges_val);
        // 初始化价格区间数组
        $need_price_ranges = [];
        
        // 定义价格区间的步长（可以根据需要调整）
        $step = 500;
        $twostep = 1000;
        
        // 计算起始区间
        $current_start  = 0;
        $current_end = 0;
        
        // 循环生成价格区间，直到覆盖到最大价格或指定的更高上限（如10000+）
        while ($current_start  <= $max_price || ($current_start  <= 10000 && $max_price > 10000)) {
            if($current_start >= 1000){
                $current_end = $current_start  + $twostep - 1;
            }else{
                $current_end = $current_start  + $step - 1;
            }
            // 如果最后一个区间需要超过10000，则设置为10000+
            if ($current_end < $max_price || ($current_end < 10000 && $max_price > 10000)) {
                $need_price_ranges["{$current_start }-{$current_end}"] = 0;
            } elseif ($current_end >= 10000) {
                // 处理超过10000的情况
                $need_price_ranges["{$current_start }+"] = 0;
                break;
            }else{
                $need_price_ranges["{$current_start }-{$current_end}"] = 0;
            }
            if($current_start >= 1000){
                $current_start  += $twostep;
            }else{
                $current_start  += $step;
            }
        }
        // 统计每个价格区间内的价格数量        
        foreach ($all_skus as $sku) {
            foreach ($need_price_ranges as $interval => &$count) {
                // print_r($explode('-', $interval));die;
                //检查价格是否属于当前区间 
                if (strpos($interval, '+') !== false) {
                    // 处理特殊区间，如 "10000+"
                    list($start) = explode('+', $interval);
                    // $start = (int)$start;
                    if (floatval($sku['price']) >= $start) {
                        $count++;
                        break;
                    }
                } else {
                    // 处理标准区间，如 "0-499"
                    list($start, $end) = explode('-', $interval);
                    // $start = (int)$start;
                    // $end = (int)$end;
                    if (floatval($sku['price']) >= $start && floatval($sku['price']) <= $end) {
                        $count++;
                        break;
                    }
                }
            }
           
        }
        // 打印结果

        // 统计价格区间
        // foreach ($all_skus as $sku) {
        //     $price = floatval($sku['price']);
        //     if ($price <= 500) {
        //         $price_ranges['0-500']++;
        //     } elseif ($price <= 1000) {
        //         $price_ranges['500-1000']++;
        //     } elseif ($price <= 2000) {
        //         $price_ranges['1000-2000']++;
        //     } elseif ($price <= 3000) {
        //         $price_ranges['2000-3000']++;
        //     } elseif ($price <= 4000) {
        //         $price_ranges['3000-4000']++;
        //     } elseif ($price <= 5000) {
        //         $price_ranges['4000-5000']++;
        //     } elseif ($price <= 6000) {
        //         $price_ranges['5000-6000']++;
        //     } elseif ($price <= 7000) {
        //         $price_ranges['6000-7000']++;
        //     } elseif ($price <= 8000) {
        //         $price_ranges['7000-8000']++;
        //     } elseif ($price <= 9000) {
        //         $price_ranges['8000-9000']++;
        //     } else {
        //         $price_ranges['9000-10000']++;
        //     }
        // }

        // // 格式化价格区间数据为图表所需格式
        // $price_chart_data = [
        //     'ranges' => array_keys($price_ranges),
        //     'counts' => array_values($price_ranges)
        // ];
        // 格式化价格区间数据为图表所需格式
        $need_price_chart_data = [
            'ranges' => array_keys($need_price_ranges),
            'counts' => array_values($need_price_ranges)
        ];

        // 统计结果
        $result = [
            'products' => $product,
            'total_factories' => count($factory_count),
            'total_city' => count($factory_count),
           // 'factory_distribution' => $factory_count,
            'city_distribution' => array_values($city_code),
            // 'price_distribution' => $price_chart_data,
            // 'price_range' => $price_ranges,
            'need_price_distribution' => $need_price_chart_data,
            'need_price_range' => $need_price_ranges,
            'total_skus' => count($all_skus)
        ];
        return JsonResponse::success($result);
        return $this->success($result);
    }

    /**
     * 上传图片
     * @return \think\Response
     */
    public function uploadImage()
    {
        try {
            // 获取上传文件
            $file = Request::file('image');
            if (!$file) {
                return JsonResponse::error('请选择要上传的图片');
            }

            // 验证文件
            $validate = Validate::rule([
                'image' => [
                    'fileSize' => 10 * 1024 * 1024, // 限制10MB
                    'fileExt'  => 'jpg,jpeg,png,gif',
                    'fileMime' => 'image/jpeg,image/png,image/gif'
                ]
            ]);

            if (!$validate->check(['image' => $file])) {
                return JsonResponse::error($validate->getError());
            }
            $realPath = $file->getRealPath();
            $md5 = md5_file($realPath);
            $getOriginalName = $file->getOriginalName();
            $existFile = Db::name('oss_file')->where('fingerprint', $md5)->whereNull('delete_time')->find();
            if($existFile){
                return JsonResponse::success([
                    'id'   => $existFile['id'],
                    'url'  => $existFile['file_url'],
                    'name' => $existFile['file_name']
                ], '上传成功');
            }
            $ext = $file->getOriginalExtension(); // 文件扩展名
            $mimeType = $file->getMime(); // MIME类型

            // 根据文件类型确定存储目录
            $fileType = $this->getFileType($ext, $mimeType);
            $path = Request::param('path', ''); // 目录路径
            if ($path) {
                if ($path === '/') $path = '';
                $fileName = $path . md5(uniqid((string)mt_rand(), true)) . '.' . $ext;
            } else {
                $fileName = "upload/" . date('Ymd') . '/' . $fileType . '/' . md5(uniqid((string)mt_rand(), true)) . '.' . $ext;
            }
            // 上传到OSS
            $result = (new OssClient())->uploadFile($realPath, $fileName);
            if (!$result) {
                return JsonResponse::error('上传失败');
            }
            list($width, $height) = getimagesize($realPath); //获取图片的高度
            // 记录文件信息到数据库 需要补全
            $fileData = [
                'file_url'     => $result,
                'fingerprint'  => $md5,
                'file_name'    => $getOriginalName,//file->getOriginalName(),//$file->getOriginalName(),
                'file_path'    => $fileName,
                'file_ext'     => $ext,
                'mime_type'    => $mimeType,
                'upload_ip'    => Request::ip(),
                'width'        => $width,
                'height'       => $height,
                'file_size'    => $file->getSize(),
                'create_time'   => date('Y-m-d H:i:s'),
                'update_time'   => date('Y-m-d H:i:s')
            ];

            
            $fileId = Db::name('oss_file')->insertGetId($fileData);

            return JsonResponse::success([
                'id'   => $fileId,
                'url'  => $result,
                'name' => $fileName
            ], '上传成功');

       } catch (\Exception $e) {
           Log::error('图片上传失败: ' . $e->getMessage());
           return JsonResponse::error('图片上传失败：' . $e->getMessage());
       }
    }

    /**
     * 上传Base64图片
     * @return \think\Response
     */
    private function uploadBase64Image($base64Data)
    {
        // try { data:image/jpeg;base64,
            // 获取base64数据
            #$base64Data = Request::post('image'); // 前端传递的base64图片数据
            
            // if (empty($base64Data)) {
            //     return JsonResponse::error('请提供图片数据');
            // }
            //data:image/jpeg;base64,
            // 处理base64数据
            // if (preg_match('/^data:image\/(\w+);base64,/', $base64Data, $matches)) {
            $type = 'jpeg'; // 获取图片类型
                // if (!in_array($type, ['jpeg', 'jpg', 'png', 'gif'])) {
                //     return JsonResponse::error('不支持的图片类型');
                // }
                
                // 去除base64图片头部信息
                // $base64Data = preg_replace('/^data:image\/\w+;base64,/', '', $base64Data);
            $imageData = base64_decode($base64Data);
            
            if ($imageData === false) {
                $result = [
                    'code' => 500,
                    'msg' => '图片解码失败'
                ];
                return $result;
            }
            // } else {
            //     return JsonResponse::error('无效的图片数据格式');
            // }

            // 生成临时文件
            $tmpFile = tempnam(sys_get_temp_dir(), 'upload_');
            file_put_contents($tmpFile, $imageData);

            // 计算文件MD5
            $md5 = md5_file($tmpFile);
            
            // 检查是否已存在相同文件
            $existFile = Db::name('oss_file')->where('fingerprint', $md5)->whereNull('delete_time')->find();
            if ($existFile) {
                // 删除临时文件
                @unlink($tmpFile);
                $result = [
                    'code' => 200,
                    'data' => [
                        'id'   => $existFile['id'],
                        'url'  => $existFile['file_url'],
                        'name' => $existFile['file_name']
                    ]
                ];
                return $result;
            }

            // 获取图片信息
            $imageInfo = getimagesize($tmpFile);
            if ($imageInfo === false) {
                @unlink($tmpFile);
                $result = [
                    'code' => 500,
                    'msg' => '无效的图片文件'
                ];
                return $result;
            }

            // 构建文件名
            $fileName = "upload/" . date('Ymd') . '/image/' . md5(uniqid((string)mt_rand(), true)) . '.' . $type;

            // 上传到OSS
            $result = (new OssClient())->uploadFile($tmpFile, $fileName);
            if (!$result) {
                @unlink($tmpFile);
                $result = [
                    'code' => 500,
                    'msg' => '上传失败'
                ];
                return $result;
            }

            // 记录文件信息到数据库
            $fileData = [
                'file_url'     => $result,
                'fingerprint'  => $md5,
                'file_name'    => $fileName,
                'file_path'    => $fileName,
                'file_ext'     => $type,
                'mime_type'    => $imageInfo['mime'],
                'upload_ip'    => Request::ip(),
                'width'        => $imageInfo[0],
                'height'       => $imageInfo[1],
                'file_size'    => strlen($imageData),
                'create_time'  => date('Y-m-d H:i:s'),
                'update_time'  => date('Y-m-d H:i:s')
            ];
            $fileId = Db::name('oss_file')->insertGetId($fileData);
            
            // 删除临时文件
            @unlink($tmpFile);

            $result = [
                'code' => 200,
                'data' => [
                    'id'   => $fileId,
                    'url'  => $result,
                    'name' => $fileName
                ]
            ];
            return $result;

        // } catch (\Exception $e) {
        //     Log::error('Base64图片上传失败: ' . $e->getMessage());
        //     return JsonResponse::error('图片上传失败：' . $e->getMessage());
        // }
    }

    /**
     * 根据文件扩展名和MIME类型获取文件类型
     * @param string $ext 文件扩展名
     * @param string $mimeType MIME类型
     * @return string
     */
    protected function getFileType($ext, $mimeType): string
    {
        // 图片类型
        $imageExts = explode(',', env('UPLOAD_IMAGE_EXT', 'jpg,jpeg,png,gif,bmp,webp'));
        if (in_array($ext, $imageExts) || strpos($mimeType, 'image/') === 0) {
            return 'image';
        }

        // 视频类型
        $videoExts = explode(',', env('UPLOAD_VIDEO_EXT', 'mp4,avi,rmvb,rm,flv,3gp'));
        if (in_array($ext, $videoExts) || strpos($mimeType, 'video/') === 0) {
            return 'video';
        }

        // 音频类型
        $audioExts = explode(',', env('UPLOAD_AUDIO_EXT', 'mp3,wav,wma,ogg,ape,acc'));
        if (in_array($ext, $audioExts) || strpos($mimeType, 'audio/') === 0) {
            return 'audio';
        }

        // 文档类型
        $documentExts = explode(',', env('UPLOAD_DOCUMENT_EXT', 'doc,docx,xls,xlsx,ppt,pptx,pdf,txt'));
        if (in_array($ext, $documentExts)) {
            return 'document';
        }

        // 压缩包类型
        $archiveExts = explode(',', env('UPLOAD_ARCHIVE_EXT', 'zip,rar,7z,gz,tar'));
        if (in_array($ext, $archiveExts)) {
            return 'archive';
        }

        // 其他类型
        return 'other';
    }

    /**
     * 留言板
     * @param RequestInterface $request
     */
    public function messageBoard()
    {
        try {
            $audio = Request::param('voice'); // base64音频数据
            $voiceFormat = Request::param('voice_format', 'mp3'); // 音频格式，默认mp3
            $EngSerViceType = Request::param('engSer_vice_type', '16k_zh');
            $userId = Request()->userId; // 假设有获取当前用户ID的方法
            $type = intval(Request::param('type', '2'));
            if (empty($audio)) {
                return JsonResponse::error('音频数据不能为空');
            }

            // 验证音频格式
            $allowFormats = ['mp3', 'wav', 'aac', 'm4a'];
            if (!in_array($voiceFormat, $allowFormats)) {
                return JsonResponse::error('不支持的音频格式');
            }

            // 解码base64数据
            $audioData = base64_decode(str_replace(['data:audio/mpeg;base64,', 'data:audio/wav;base64,', 'data:audio/aac;base64,'], '', $audio));
            if (!$audioData) {
                return JsonResponse::error('音频数据解码失败');
            }

            // 生成临时文件
            $tempDir = runtime_path() . 'temp/';
            if (!is_dir($tempDir)) {
                mkdir($tempDir, 0777, true);
            }

            // 生成临时输入文件
            $tempFile = $tempDir . md5(uniqid()) . '.temp';
            file_put_contents($tempFile, $audioData);

            // 生成输出文件名
            $outputFile = $tempDir . md5(uniqid()) . '.' . $voiceFormat;

            // 构建 FFmpeg 命令
            $ffmpegBin = '/www/server/ffmpeg/ffmpeg-6.1/ffmpeg';
            
            // 根据不同格式设置不同的参数
            switch ($voiceFormat) {
                case 'mp3':
                    $command = sprintf('%s -i %s -acodec libmp3lame -ar 44100 -ab 128k -ac 2 %s', 
                        $ffmpegBin, $tempFile, $outputFile);
                    break;
                case 'wav':
                    $command = sprintf('%s -i %s -acodec pcm_s16le -ar 44100 -ac 2 %s', 
                        $ffmpegBin, $tempFile, $outputFile);
                    break;
                case 'aac':
                    $command = sprintf('%s -i %s -acodec aac -ar 44100 -ab 128k -ac 2 %s', 
                        $ffmpegBin, $tempFile, $outputFile);
                    break;
                case 'm4a':
                    $command = sprintf('%s -i %s -acodec aac -ar 44100 -ab 128k -ac 2 -f mp4 %s', 
                        $ffmpegBin, $tempFile, $outputFile);
                    break;
                default:
                    $command = sprintf('%s -i %s -acodec libmp3lame -ar 44100 -ab 128k -ac 2 %s', 
                        $ffmpegBin, $tempFile, $outputFile);
            }

            // 执行命令
            $output = [];
            $returnVar = 0;
            exec($command . ' 2>&1', $output, $returnVar);
            // 检查命令执行结果
            if ($returnVar !== 0) {
                throw new \Exception('音频转换失败: ' . implode("\n", $output));
            }

            // 获取转换后的音频信息
            // $probeCommand = sprintf('/www/server/ffmpeg/ffmpeg-6.1/ffprobe -v quiet -print_format json -show_format -show_streams %s',$outputFile);
            // $probeOutput = [];
            // exec($probeCommand, $probeOutput);
            // $audioInfo = json_decode(implode('', $probeOutput), true);
            // 上传到OSS
            $ossPath = 'audio/' . date('Ym') . '/' . md5(uniqid()) . '.' . $voiceFormat;
            
            $result = (new OssClient())->uploadFile($outputFile, $ossPath);
            //$result = OssUtil::uploadFile($outputFile, $ossPath);
            
            if (!$result) {
                throw new \Exception('上传OSS失败');
            }
            $audio_text='';
            $t = (new TencentService())->SpeechFromBase64($audio,$EngSerViceType,$voiceFormat,$type);
            if (isset($t['Result'])) {
                $audio_text = $t['Result'];
            }

            // 保存到数据库
            $audioRecord = [
                'user_id' => $userId,
                'audio_base64' => env('OSS_DOMAIN') . $ossPath,
                'audio_text' => $audio_text, // 如果需要语音识别，可以在这里添加
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];

            $recordId = Db::name('audio_records')->insertGetId($audioRecord);

            //解析语音中的文字

            // 清理临时文件
            @unlink($tempFile);
            @unlink($outputFile);

            // 返回结果
            // [
            //     // 'record_id' => $recordId,
            //     // // 'audio_url' => env('OSS_DOMAIN') . $ossPath,
            //     // // 'audio_text' => $audio_text, // 如果需要语音识别，可以在这里添加
            //     // 'format' => $voiceFormat,
            //     // 'duration' => $audioInfo['format']['duration'] ?? 0,
            //     // 'size' => $audioInfo['format']['size'] ?? 0,
            //     // 'bit_rate' => $audioInfo['format']['bit_rate'] ?? 0
            // ]
            return JsonResponse::success('留言成功');

        } catch (\Exception $e) {
            // 确保清理临时文件
            if (isset($tempFile) && file_exists($tempFile)) {
                @unlink($tempFile);
            }
            if (isset($outputFile) && file_exists($outputFile)) {
                @unlink($outputFile);
            }
            
            return JsonResponse::error($e->getMessage());
        }
    }

    /**
     * 视频介绍
     */
    public function VideoDesc() {
        $arr = [
            'pc_url' => "https://sanyanhu.oss-cn-shenzhen.aliyuncs.com/furnitureStaff/video/video-cover.png",
            'voice_url' => 'https://sanyanhu.oss-cn-shenzhen.aliyuncs.com/furnitureStaff/video/家具参谋操作指南.mp4',
        ];

        return JsonResponse::success($arr);
    }
} 
